package com.app.micaihu.view.main.game.view;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;

import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.comment.CommentList;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.LoadMoreView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.micaihu.view.main.game.adapter.GameCommentAdapter;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Guo on 2017/3/14.
 */

public class GameCommentListView extends ListView implements AbsListView.OnScrollListener,View.OnClickListener{
    //控件变量
    LoadMoreView loadMoreView;//加在更多的view

    //逻辑变量
    private boolean isRefreshing;//是否正在刷新
    private int mDataPage = 1;//当前页数
    private String mNewsId;//新闻id
    private Activity mActivity;
    private String mRequestName;//请求标识
    private boolean isAutoLoadMore = true;//是否自动加载下一页
    private int addCommentIndex;//添加评论下标

    private List<NewsComment> mCommentList;//新闻评论集合
    //适配器
    private GameCommentAdapter mCommentAdapter;//评论适配器

    public GameCommentListView(Context context) {
        super(context);
        initView(context);
    }

    public GameCommentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public GameCommentListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }




    /**
     * 初始化配置view
     *
     * @param context
     */
    private void initView(Context context) {
        setVerticalScrollBarEnabled(false);
        loadMoreView = new LoadMoreView(context);
        loadMoreView.setErrorPageOnClickListener(this);
        addFooterView(loadMoreView);
        this.setOnScrollListener(this);
    }


    /**
     * 开始加载数据
     * @param activity
     * @param newsId
     */
    public void startLoadData(Activity activity, String newsId,String requestName) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        this.mActivity = activity;
        this.mNewsId = newsId;
        this.mRequestName = requestName;
        mCommentList = new ArrayList<NewsComment>();
        mCommentAdapter = new GameCommentAdapter(mCommentList, mActivity);
        setAdapter(mCommentAdapter);
        //加载数据
        mDataPage = 1;
        addCommentIndex = 0;
        loadCommentData();
    }


    /**
     * 重置数据
     * @param activity
     * @param newsId
     */
    public void startResetData(Activity activity, String newsId,String requestName) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        this.mActivity = activity;
        this.mNewsId = newsId;
        this.mRequestName = requestName;
        if(mCommentList == null){
            mCommentList = new ArrayList<NewsComment>();
        }else {
            mCommentList.clear();
        }
        if(mCommentAdapter == null){
            mCommentAdapter = new GameCommentAdapter(mCommentList, mActivity);
        }
        if(getAdapter() == null){
            setAdapter(mCommentAdapter);
        }else{
            mCommentAdapter.notifyDataSetChanged();
        }
        //加载数据
        mDataPage = 1;
        loadCommentData();
    }

    /**
     * 设置刷新中
     *
     * @param msg
     */
    public void onRefreshing(String msg) {
        if (this.loadMoreView != null) {
            this.loadMoreView.showLoading(msg);
            this.isRefreshing = true;
        }
    }

    /**
     * 刷新完成
     */
    private void onComplete(int type, String msg) {
        if (this.loadMoreView != null) {
            switch (type) {
                case 1://加载成功
                    this.loadMoreView.showSuccess();
                    break;
                case 2://加载错误
                    this.loadMoreView.showErrorPage(msg);
                    break;
                case 3://空数据
                    this.loadMoreView.showEmptyPage();
                    break;
            }

            this.isRefreshing = false;
        }
    }

    /**
     * 设置底部背景颜色
     * @param resourceId
     */
    public void setFootViewColor(int resourceId){
        if(loadMoreView != null){
            loadMoreView.setBackgroundColor(getResources().getColor(resourceId));
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        //当滑动停止并且滑动到底部时加载更多数据
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getLastVisiblePosition() >= (view.getCount() - 2)) {
                onRefreshMore();
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    /**
     * 加载更多
     */
    public void onRefreshMore() {
        if (isRefreshing() || !isAutoLoadMore) {
            return;
        }
        mDataPage++;
        loadCommentData();
    }

    /**
     * 加载评论
     */
    private void loadCommentData() {
        if (TextUtils.isEmpty(mNewsId)) {
            return;
        }
        HashMap<String, String> parms = new HashMap<String, String>();
        parms.put("articleId", mNewsId);
        parms.put("page", mDataPage + "");
        if(UserInforManager.getInstance().isLogin()){
            parms.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }


        HttpListener<DataBean<CommentList>> httpListener = new HttpListener<DataBean<CommentList>>() {

            @Override
            public void onStart() {
                //设置正在刷新
                onRefreshing(null);
            }

            @Override
            public void onError(VolleyError error) {
                //设置刷新状态
                onComplete(2,null);
            }

            @Override
            public void onSuccess(DataBean<CommentList> response) {
                int  type;
                String msg = null;
                if (response.noError()) {
                    if (mCommentList == null) {
                        mCommentList = new ArrayList<NewsComment>();
                    }
                    if (mCommentAdapter == null) {
                        mCommentAdapter = new GameCommentAdapter(mCommentList, mActivity);
                        setAdapter(mCommentAdapter);
                    }
                    CommentList commentList = response.getData();

                    //去除黑名单的数据
                    if(commentList.getHotCmtList() != null && commentList.getHotCmtList().size()>0){
                        for (int i = 0; i< commentList.getHotCmtList().size();i++) {
                            if(InteractiveUtils.getInstance().theDefriendIsContains(commentList.getHotCmtList().get(i).getUid())){
                                commentList.getHotCmtList().remove(commentList.getHotCmtList().get(i));
                                i--;
                            }
                        }
                    }
                    if(commentList.getNormalCmtList() != null && commentList.getNormalCmtList().size()>0) {
                        for (int i = 0; i< commentList.getNormalCmtList().size();i++) {
                            if(InteractiveUtils.getInstance().theDefriendIsContains(commentList.getNormalCmtList().get(i).getUid())){
                                commentList.getNormalCmtList().remove(commentList.getNormalCmtList().get(i));
                                i--;
                            }
                        }
                    }


                    List<NewsComment> list = null;
                    if(commentList != null){
                        //设置添加评论的坐标
                        if(addCommentIndex == 0){
                            //如果addCommentIndex==0说明这是第一次配置数据
                            if(commentList.getHotCmtList() != null
                                    && commentList.getHotCmtList().size() > 0){
                                addCommentIndex = commentList.getHotCmtList().size()+2;
                                mCommentAdapter.currentLastHotIndex = commentList.getHotCmtList().size();
                            }else{
                                addCommentIndex = 1;
                            }
                            list = commentList.getAllCommentList();
                        }else{
                            //加载下一页的时候只拿最新评论
                            list = commentList.getNormalCmtList();
                        }

                    }
                    if (list != null && list.size() > 0) {
                        mCommentList.addAll(list);
                        mCommentAdapter.notifyDataSetChanged();
                        type = 1;
                        isAutoLoadMore = true;
                    } else if (mCommentList != null && mCommentList.size() > 0) {
                        //展示没有更多评论
                        isAutoLoadMore = false;
                        msg = AppApplication.getInstance().getString(R.string.comment_data_empty);
                        type = 2;
                    } else {
                        if(mCommentList.size() == 0){
                            //只配置一个最新评论的title
                            NewsComment newsComment = new NewsComment();
                            newsComment.setCommentTypeName("最新评论");
                            mCommentList.add(newsComment);
                            mCommentAdapter.notifyDataSetChanged();
                        }

                        //展示暂无评论
                        isAutoLoadMore = false;
                        type = 3;
                    }
                } else {
                    //当前没有评论则显示加载错误
                    type = 2;
                }
                //解除刷新状态
                onComplete(type,msg);
            }
        };

        HttpUtils.addPostRequest(URIContant.NEWSCOMMENTLIST, new TypeToken<DataBean<CommentList>>() {
        }.getType(), mRequestName, parms, httpListener);
    }


    /**
     * 增加评论
     * @param newsComment
     */
    public void addComment(NewsComment newsComment){
        if(mCommentList == null){
            mCommentList = new ArrayList<NewsComment>();
        }
        if(mCommentList.size() == 0){
            NewsComment comment = new NewsComment();
            comment.setCommentTypeName("最新评论");
            mCommentList.add(comment);
        }
        try {
            mCommentList.add(addCommentIndex, newsComment);
        }catch (IndexOutOfBoundsException e){
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        if(mCommentAdapter == null){
            mCommentAdapter = new GameCommentAdapter(mCommentList,mActivity);
            setAdapter(mCommentAdapter);
        }else{
            mCommentAdapter.notifyDataSetChanged();
        }
        onComplete(1, "");
    }

    public boolean isRefreshing() {
        return isRefreshing;
    }

    public void setIsRefreshing(boolean isRefreshing) {
        this.isRefreshing = isRefreshing;
    }

    @Override
    public void onClick(View v) {
        if(v == null){
            return;
        }
        //错误点击
        if(v.getId() == R.id.load_error_page){
            loadCommentData();
        }
    }

    /**
     * 设置空数据时的点击
     * @param onClickListener
     */
    public void setEmptyViewOnClickListener(View.OnClickListener onClickListener){
        if(loadMoreView != null){
            loadMoreView.setEmptyPageOnClickListener(onClickListener);
        }
    }

    /**
     * 是否改变点赞数
     * @param isChange
     */
    public void notifyZanData(boolean isChange){
        if(!isChange){
            return;
        }
        if(mCommentAdapter != null){
            mCommentAdapter.notifyZanComment();
        }
    }

}
